package asia.yuanding.wechat.system.util;

import asia.yuanding.wechat.web.entity.User;
import asia.yuanding.wechat.web.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @ClassName: EmailUtil
 * @Author: YuanDing
 * @Date: 2025/7/26 15:25
 * @Description:
 */

@Slf4j
@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String senderEmail;

    @Resource
    private UserMapper userMapper;

    /**
     * 发送验证码邮件（微信风格）
     */
    public void sendCode(String toEmail, String code) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom(senderEmail);
        helper.setTo(toEmail);
        helper.setSubject("【微信】验证码通知");

        String html = buildHtml(code);
        helper.setText(html, true);

        mailSender.send(message);
    }

    /**
     * 生成微信风格 HTML
     */
    private String buildHtml(String code) {
        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE html>")
                .append("<html lang='zh-CN'><head><meta charset='UTF-8'><title>验证码</title></head>")
                .append("<body style='font-family: Arial, sans-serif; background-color: #f4f5f7; padding: 30px;'>")
                .append("<div style='max-width: 500px; margin: 0 auto; background: #fff; border-radius: 10px; padding: 25px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);'>")
                .append("<div style='text-align: center; margin-bottom: 20px;'>")
                .append("<img src='https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico' width='50' alt='微信图标'/>")
                .append("<h2 style='margin-top: 10px; color: #07c160;'>微信安全验证码</h2>")
                .append("</div>")
                .append("<p style='font-size: 16px; color: #333;'>您好，感谢使用微信服务！</p>")
                .append("<p style='font-size: 16px; color: #333;'>您的验证码为：</p>")
                .append("<p style='font-size: 28px; font-weight: bold; color: #07c160; text-align: center; letter-spacing: 4px; margin: 20px 0;'>")
                .append(code)
                .append("</p>")
                .append("<p style='font-size: 14px; color: #666;'>此验证码 5 分钟内有效，请勿泄露给他人。</p>")
                .append("<hr style='border: none; border-top: 1px solid #eee; margin: 20px 0;'>")
                .append("<p style='font-size: 12px; color: #999; text-align: center;'>")
                .append("本邮件由系统自动发送，请勿回复。<br/>© 微信 WeChat(假滴 嘿嘿)")
                .append("</p></div></body></html>");
        return sb.toString();
    }

    /**
     * 发送好友申请邮件（微信风格）
     */
    public void sendFriendRequest(String toEmail, String applyUserNickname, String targetUserNickname) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom(senderEmail);
        helper.setTo(toEmail);
        helper.setSubject("【微信】好友申请通知");

        String html = buildFriendRequestHtml(applyUserNickname, targetUserNickname);
        helper.setText(html, true);

        mailSender.send(message);
    }

    /**
     * 生成好友申请邮件的微信风格 HTML
     */
    private String buildFriendRequestHtml(String applyUserNickname, String targetUserNickname) {
        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE html>")
                .append("<html lang='zh-CN'><head><meta charset='UTF-8'><title>好友申请</title></head>")
                .append("<body style='font-family: Arial, sans-serif; background-color: #f4f5f7; padding: 30px;'>")
                .append("<div style='max-width: 500px; margin: 0 auto; background: #fff; border-radius: 10px; padding: 25px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);'>")
                .append("<div style='text-align: center; margin-bottom: 20px;'>")
                .append("<img src='https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico' width='50' alt='微信图标'/>")
                .append("<h2 style='margin-top: 10px; color: #07c160;'>微信好友申请</h2>")
                .append("</div>")
                .append("<div style='background: #f8f9fa; border-radius: 8px; padding: 20px; margin: 20px 0;'>")
                .append("<p style='font-size: 16px; color: #333; margin: 0;'>Hi ").append(targetUserNickname).append("，</p>")
                .append("<p style='font-size: 16px; color: #333; margin: 10px 0;'>")
                .append("<strong style='color: #07c160;'>").append(applyUserNickname).append("</strong> 想要添加您为好友")
                .append("</p>")
                .append("</div>")
                .append("<div style='text-align: center; margin: 25px 0;'>")
                .append("<div style='display: inline-block; background: #07c160; color: white; padding: 12px 30px; border-radius: 25px; font-size: 16px; font-weight: bold;'>")
                .append("👥 新的好友申请")
                .append("</div>")
                .append("</div>")
                .append("<p style='font-size: 14px; color: #666; text-align: center;'>")
                .append("请登录微信查看详情并处理好友申请")
                .append("</p>")
                .append("<hr style='border: none; border-top: 1px solid #eee; margin: 20px 0;'>")
                .append("<p style='font-size: 12px; color: #999; text-align: center;'>")
                .append("本邮件由系统自动发送，请勿回复。<br/>© 微信 WeChat(假滴 嘿嘿)")
                .append("</p></div></body></html>");
        return sb.toString();
    }

    @Async
    public void sendContactApply(String applyId , String targetId) {
        try {



            User applyUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getUid , applyId));

            User targetUser = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getUid , targetId));

            // 推送人姓名
            String nickname = applyUser.getNickname();

            // 推送邮箱
            String email = targetUser.getEmail();

            // 发送好友申请邮件
            if (email != null && !email.isEmpty()) {
                sendFriendRequest(email, nickname, targetUser.getNickname());
            }
        } catch (Exception e) {
            // 记录日志，但不影响主流程
            log.error("发送好友申请邮件失败:{} " , e.getMessage());
            e.printStackTrace();
        }
    }

    @Async
    public void sendHandleApplyNotice(String applyId, String contactRemark) {
        try {
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getUid, applyId));
            String nickname = user.getNickname();
            String email = user.getEmail();

            // 发送好友通过邮件
            if (email != null && !email.isEmpty()) {
                sendFriendApprovalNotice(email, nickname, contactRemark);
            }
        } catch (Exception e) {
            // 记录日志，但不影响主流程
            log.error("发送好友通过邮件失败:{} ", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 发送好友申请通过邮件（微信风格）
     */
    public void sendFriendApprovalNotice(String toEmail, String nickname, String contactRemark) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        helper.setFrom(senderEmail);
        helper.setTo(toEmail);
        helper.setSubject("【微信】好友申请已通过");

        String html = buildFriendApprovalHtml(nickname, contactRemark);
        helper.setText(html, true);

        mailSender.send(message);
    }

    /**
     * 生成好友申请通过邮件的微信风格 HTML
     */
    private String buildFriendApprovalHtml(String nickname, String contactRemark) {
        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE html>")
                .append("<html lang='zh-CN'><head><meta charset='UTF-8'><title>好友申请通过</title></head>")
                .append("<body style='font-family: Arial, sans-serif; background-color: #f4f5f7; padding: 30px;'>")
                .append("<div style='max-width: 500px; margin: 0 auto; background: #fff; border-radius: 10px; padding: 25px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);'>")
                .append("<div style='text-align: center; margin-bottom: 20px;'>")
                .append("<img src='https://res.wx.qq.com/a/wx_fed/assets/res/NTI4MWU5.ico' width='50' alt='微信图标'/>")
                .append("<h2 style='margin-top: 10px; color: #07c160;'>微信好友申请通过</h2>")
                .append("</div>")
                .append("<div style='background: #f0f9ff; border-left: 4px solid #07c160; padding: 20px; margin: 20px 0;'>")
                .append("<p style='font-size: 16px; color: #333; margin: 0;'>Hi ").append(nickname).append("，</p>")
                .append("<p style='font-size: 16px; color: #333; margin: 10px 0;'>")
                .append("恭喜！您的好友申请已通过 🎉")
                .append("</p>");
        
        if (contactRemark != null && !contactRemark.isEmpty()) {
            sb.append("<p style='font-size: 16px; color: #333; margin: 10px 0;'>")
                    .append("您现在可以和 <span style='color: #07c160; font-weight: bold;'>").append(contactRemark).append("</span> 开始聊天了！")
                    .append("</p>");
        }
        
        sb.append("</div>")
                .append("<div style='text-align: center; margin: 25px 0;'>")
                .append("<div style='display: inline-block; background: #07c160; color: white; padding: 12px 30px; border-radius: 25px; font-size: 16px; font-weight: bold;'>")
                .append("✅ 已成为好友")
                .append("</div>")
                .append("</div>")
                .append("<p style='font-size: 14px; color: #666; text-align: center;'>")
                .append("现在您可以开始聊天了！")
                .append("</p>")
                .append("<hr style='border: none; border-top: 1px solid #eee; margin: 20px 0;'>")
                .append("<p style='font-size: 12px; color: #999; text-align: center;'>")
                .append("本邮件由系统自动发送，请勿回复。<br/>© 微信 WeChat(假滴 嘿嘿)")
                .append("</p></div></body></html>");
        return sb.toString();
    }
}
